package cn.xz.nearby.service.impl;

import cn.xz.nearby.entity.Point;
import cn.xz.nearby.entity.UserLocation;
import cn.xz.nearby.mapper.UserLocationRepository;
import cn.xz.nearby.service.IUserLocationService;
import cn.xz.nearby.util.BaiduMapUtil;
import cn.xz.nearby.vo.UserLocationVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
public class UserLocationServiceImpl implements IUserLocationService {

    @Autowired
    private UserLocationRepository userLocationRepository;
    @Override
    public void add(UserLocationVo userLocationVo) {
        UserLocation userLocation = new UserLocation();
        userLocation.setUserId(userLocationVo.getUserId());
        userLocation.setAddress(userLocationVo.getAddress());
        Point point = BaiduMapUtil.getPoint(userLocation.getAddress());
        userLocation.setPoint(point);
        userLocation.setCreated(new Date().getTime());
        userLocation.setUpdated(new Date().getTime());
        userLocationRepository.save(userLocation);
    }

    @Override
    public void update(UserLocationVo userLocationVo) {
        UserLocation userLocation = userLocationRepository.findByUserId(userLocationVo.getUserId());
        userLocation.setAddress(userLocation.getAddress());
        userLocation.setUpdated(new Date().getTime());
        userLocation.setLastUpdated(new Date().getTime());
        userLocationRepository.save(userLocation);
    }

    @Override
    public void delete(String id) {
        userLocationRepository.deleteById(id);
    }

    @Override
    public UserLocation queryOne(String id) {
        return userLocationRepository.findById(id).get();
    }

    @Override
    public List<UserLocation> queryAll() {
        return userLocationRepository.findAll();
    }

    /**
     * 查询当前用户附近的人
     * @param userLocationVo
     * @return
     */
    @Override
    public List<UserLocation> getNearByUser(UserLocationVo userLocationVo) {

        List<UserLocation> userLocations = userLocationRepository.findAll();
        Point currentPoint = BaiduMapUtil.getPoint(userLocationVo.getAddress());
        List<UserLocation> nearbyUsers = new ArrayList<>();
        for (UserLocation userLocation : userLocations) {
            Point otherPoint = BaiduMapUtil.getPoint(userLocation.getAddress());
            double distance = BaiduMapUtil.getDistance(currentPoint, otherPoint);
            if (distance < 20000){
                nearbyUsers.add(userLocation);
            }
        }

        return nearbyUsers;
    }
}
